<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Validator;
use Illuminate\Http\Request;
use App\Libraries\Weixin;
use DB;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WechatOrder;
use QrCode;
use App\Models\QrcodeToken;
use App\Models\User;
use App\Models\Door;
use App\Models\Order;
use App\Models\Goods;
use App\Models\OrderDetail;
use App\Models\GoodsNexus;

class OrderController extends Controller {

    //订单列表
    public function orderList(Request $request, Application $wechat) {
        $validator = Validator::make($request->all(), [
                    'order_id' => 'required|integer'
        ]);
        if ($validator->fails()) {
            $errorMsg = $validator->errors()->all();
            //如果验证未通过，返回第一条错误信息
            return ['status' => 0, 'msg' => $errorMsg[0]];
        }
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'order_list?order_id=' . $request->input('order_id')]);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $orderDetail = OrderDetail::where('order_id', $request->input('order_id'))->get();
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        $order = Order::find($request->input('order_id'));
        if (!$order) {
            return ['status' => 0, 'msg' => '该订单不存在'];
        } elseif ($order->user_id != $user->id) {
            return ['status' => 0, 'msg' => '该订单不是您的订单'];
        }
        $orderList = [];
        $goodsIdsAndAmount = [];
        foreach ($orderDetail as $orderdetail) {
            $goodsNexus = GoodsNexus::where('rfid', $orderdetail->rfid)->first();
            if (!array_key_exists($goodsNexus->goods_id, $goodsIdsAndAmount)) {
                $goodsIdsAndAmount[$goodsNexus->goods_id] = 1;
            } else {
                $goodsIdsAndAmount[$goodsNexus->goods_id] = $goodsIdsAndAmount[$goodsNexus->goods_id] + 1;
            }
        }
        $i = 0;
        foreach ($goodsIdsAndAmount as $goodsId => $goodsAmount) {
            $goods = Goods::find($goodsId);
            $orderList[$i]['goods_id'] = $goods->id;
            $orderList[$i]['goods_img'] = $goods->img;
            $orderList[$i]['goods_name'] = $goods->name;
            $orderList[$i]['goods_subamount'] = $goodsAmount;
            $orderList[$i]['goods_subtotal'] = $goodsAmount * $goods->price;
            $i++;
        }
        $viewData = [
            'order_id' => $request->input('order_id'),
            'order_num' => $order->order_num,
            'orderList' => $orderList,
            'total' => $order->total,
            'isPay' => $order->state,
        ];
        if ($order->state == 0) {
            $attributes = [
                'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
                'body' => '无人商店',
                'detail' => '无人商店',
                'out_trade_no' => $order->order_num,
                'total_fee' => ($order->total)*100, // 单位：分
                'notify_url' => env('APP_URL') . '/order_notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid' => session('wechat_userinfo.openid'), // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            ];
            $payment = $wechat->payment;
            $orderData = new WechatOrder($attributes);
            $result = $payment->prepare($orderData);
            \Log::info('订单号:'.$order->order_num);
            \Log::info($result);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
                $prepayId = $result->prepay_id;
                $paymentjson = $payment->configForPayment($prepayId);
                $viewData['paymentjson'] = $paymentjson;
                $viewData['once'] = $request->input('once');
                return view('wechat.order.orderList', $viewData);
            }else{
                return $result->toArray();
            }
            
        }
        
    }

    //微信支付异步通知
    public function orderNotify(Request $request, Application $wechat) {
        $response = $wechat->payment->handleNotify(function($notify, $successful) {
            log::info('-------------------微信支付异步通知开始-------------------');
            log::info($notify);
            log::info('-------------------微信支付异步通知结束-------------------');
            $order = Order::where('order_num', $notify['out_trade_no'])->first();
            if (!$order) {
                return '订单不存在';
            }
            if ($order->state == 1) {
                return true;
            }
            if ($successful) {
                $order->state = 1;
                $order->wx_transaction_id = $notify['transaction_id'];
                $order->pay_time = $notify['time_end'];
                $order->save();
            }
            return true;
        });
        return $response;
    }

    //支付成功页
    public function paySuccess(Request $request, Application $wechat) {
        $order = Order::find($request->input('order_id'));
        if (!$order) {
            return ['status' => 0, 'msg' => '订单不存在'];
        }
        if ($order->state == 0) {
            return ['status' => 0, 'msg' => '订单未支付'];
        }
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'pay_success?order_id=' . $request->input('order_id')]);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        if ($user->id != $order->user_id) {
            return ['status' => 0, 'msg' => '该订单不属于您'];
        }
        return view('wechat.order.paySuccess', [
            'order_id' => $order->id,
            'total' => $order->total,
            'order_num' => $order->order_num
        ]);
    }

    //订单详情
    public function orderDetail(Request $request, Application $wechat) {
        $order = Order::find($request->input('order_id'));
        if (!$order) {
            return ['status' => 0, 'msg' => '订单不存在'];
        }
        if (empty(session('wechat_userinfo'))) {
            session(['target_url' => 'order_detail?order_id=' . $request->input('order_id')]);
            return $wechat->oauth->scopes(['snsapi_userinfo'])
                            ->redirect();
        }
        $user = User::where('openid', session('wechat_userinfo.openid'))->first();
        if ($user->id != $order->user_id) {
            return ['status' => 0, 'msg' => '该订单不属于您'];
        }
        $orderList = [];
        $goodsIdsAndAmount = [];
        $orderDetail = OrderDetail::where('order_id', $request->input('order_id'))->get();
        foreach ($orderDetail as $orderdetail) {
            $goodsNexus = GoodsNexus::where('rfid', $orderdetail->rfid)->first();
            if (!in_array($goodsNexus->goods_id, $goodsIdsAndAmount)) {
                $goodsIdsAndAmount[$goodsNexus->goods_id] = 1;
            } else {
                $goodsIdsAndAmount[$goodsNexus->goods_id] = $goodsIdsAndAmount[$goodsNexus->goods_id] + 1;
            }
        }
        $i = 0;
        foreach ($goodsIdsAndAmount as $goodsId => $goodsAmount) {
            $goods = Goods::find($goodsId);
            $orderList[$i]['goods_id'] = $goods->goods_id;
            $orderList[$i]['goods_name'] = $goods->name;
            $orderList[$i]['goods_subamount'] = $goodsAmount;
            $orderList[$i]['goods_subtotal'] = $goodsAmount * $goods->price;
            $i++;
        }
        $viewData = [
            'order_id' => $request->input('order_id'),
            'order_num' => $order->order_num,
            'orderList' => $orderList,
            'total' => $order->total,
            'isPay' => $order->state,
        ];
        return view('wechat.order.orderDetail', $viewData);
    }

}
